package droid.insane.GUI;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.AlertDialog.Builder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import droid.insane.communication.Communicator;
import droid.insane.database.DBHandler;
import droid.insane.logic.ConstantValues;
import droid.insane.logic.ExtendedListView;
import droid.insane.logic.R;
import droid.insane.logic.UpdateFlags;

/**
 * @author Sandamal
 *This ACtivity displays current market data
 */
public class MarketDataWindow extends ListActivity {

	private DBHandler dbHandler;
	private static ArrayList<String[]> companyList;
	private ExtendedListView mAdapter;
	private Handler handler;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.marketdata);
		final ListView lv = getListView();
		registerForContextMenu(lv);
		
		//When an item on the list is selected
		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				showCompanyInfo(arg2 + 1);
			}

		});
		getDataFromDB();
		mAdapter = new ExtendedListView(this, companyList, R.layout.listentry);
		setListAdapter(mAdapter);
	}

	/**
	 * @param companyRow - The row index of the row in the database
	 * This method opens a dialog and displays company data
	 */
	public void showCompanyInfo(final int companyRow) {
		AlertDialog.Builder companyInfoDialog = new Builder(this);
		companyInfoDialog.setCancelable(true);
		companyInfoDialog.setIcon(R.drawable.ic_menu_buy);

		LayoutInflater factory = LayoutInflater.from(this);
		final View companyDataView = factory.inflate(
				R.layout.companymarketdata, null);
		companyInfoDialog.setView(companyDataView);

		final TextView edtSymbol = (TextView) companyDataView
				.findViewById(R.id.txvTitle);
		final TextView edtName = (TextView) companyDataView
				.findViewById(R.id.txvDescription);
		final TextView edtOpen = (TextView) companyDataView
				.findViewById(R.id.txvOpen);
		final TextView edtHigh = (TextView) companyDataView
				.findViewById(R.id.txvHigh);
		final TextView edtLow = (TextView) companyDataView
				.findViewById(R.id.txvLow);
		final TextView edtPrevClose = (TextView) companyDataView
				.findViewById(R.id.txvPreviousClose);
		final TextView edtLastTraded = (TextView) companyDataView
				.findViewById(R.id.txvLastTraded);
		final TextView edtChange = (TextView) companyDataView
				.findViewById(R.id.txvChange);

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				Bundle b = msg.getData();
				String[] temp = b.getStringArray(ConstantValues.DATA);
				edtSymbol.setText(temp[0]);
				edtName.setText(temp[1]);
				edtOpen.setText(temp[2]);
				edtHigh.setText(temp[3]);
				edtLow.setText(temp[4]);
				edtPrevClose.setText(temp[5]);
				edtLastTraded.setText(temp[6]);
				edtChange.setText(temp[7]);

			}
		};
		Thread t = new Thread() {
			@Override
			public void run() {
				Message message = new Message();
				Bundle b = new Bundle();
				dbHandler = DBHandler.getDBHandler(null);
				try {
					//Retrieves company data from the database
					dbHandler.openToRead();
					String[] arr = dbHandler.getCompanyInfo(companyRow);
					dbHandler.close();
					b.putStringArray(ConstantValues.DATA, arr);
					message.setData(b);
					handler.sendMessage(message);

				} catch (Exception e) {
					Log.e(ConstantValues.TAG, e.getMessage());
				}

			};
		};
		t.start();

		companyInfoDialog.create();//Creates the dialogbox
		companyInfoDialog.show();//Shows it

	}

	/**
	 * If the database is updated the display is updated via this method
	 */
	private void updateDisplay() {
		getDataFromDB();
		mAdapter.updateDataset(companyList);
	}

	/**
	 * @return true if success
	 */
	private boolean getDataFromDB() {
		// open the data base to read values
		dbHandler = DBHandler.getDBHandler(this);
		try {
			dbHandler.openToRead();
			companyList = dbHandler.getMarketData();
			dbHandler.close();
			return true;
		} catch (Exception e) {
			Log.e(ConstantValues.TAG, e.getMessage());
			return false;
		}

	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.market_data_menu, menu);
		return true;
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.itm_update_data:
			new Communicator(this).execute(new Void[] {});
			updateDisplay();
			UpdateFlags.setMARKET_DATA_FLAG(false);
			return true;

		default:
			return false;
		}

	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		if (UpdateFlags.isMARKET_DATA_FLAG()) {
			updateDisplay();
			UpdateFlags.setMARKET_DATA_FLAG(false);
		}
		super.onResume();
	}
}